// pages/giftSel/giftgiftSel.js
const app = getApp()
var api = require('../../../utils/api.js')
var util = require('../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    autoplay: false,
    circular: false,
    lastTime: 0,
    current: 0,
    indicatorDots: true,
    items: [],
    jiugui_items: [],
    jiugui_page: 1,
    jiugui_total_page: 0,
    pingtai_page: 1,
    pingtai_total_page:0,
    pingtai_items: [],
    total_num: 0,
    total_price: 0,
    limit: 10,
    show_type: 1, //1:酒柜 2:平台
    buyGoods: [], //购买商品列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      cardId: options.id
    })
    if (options.sku_code){
      this.setData({
        sku_code: options.sku_code
      })
    }
    this.cardImage();
    this.wineList();
    this.goodsList();
  },

  changeType: function (e) {
    var that = this;
    this.setData({
      show_type: e.currentTarget.dataset.type,
      items: (e.currentTarget.dataset.type == 1 ? that.data.jiugui_items : that.data.pingtai_items)
    })
  },

  //页面上拉触底
  onReachBottom: function (e) {
    this.loadMore();
  },

  //加载更多
  loadMore: function () {
    var that=this;
    if (that.data.show_type==1){
      if (this.data.jiugui_page >= this.data.jiugui_total_page) {
        return;
      }
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        jiugui_page: this.data.jiugui_page + 1
      });
      this.wineList();
    }else{
      if (this.data.pingtai_page >= this.data.pingtai_total_page) {
        return;
      }
      wx.showLoading({
        title: '加载中',
      })
      this.setData({
        pingtai_page: this.data.pingtai_page + 1
      });
      this.goodsList();
    }
  },
  //卡面图片列表
  cardImage: function () {
    var that = this;
    api.POST({
      params: {
        cid: that.data.cardId,
      },
      url: app.globalData.base_url + 'Giftcard/details',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            cardImage: res.data.data.img_list
          });
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("请检查网络");
      }
    })
  },

  //酒柜列表
  wineList: function () {
    var that = this;
    api.POST({
      params: {
        page: that.data.jiugui_page,
        limit: that.data.limit,
        status: 1
      },
      url: app.globalData.base_url + 'winecabinet/index',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.paging;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var count = paging.count;
          var resultList = res.data.data.list;
          resultList = that.doData(resultList);
          if (currentPage == 1) {
            var itemData = resultList;
            if (itemData.length >= 1) {
              //有数据
            } else {
              //无数据
            }
          } else {
            var itemData = that.data.jiugui_items.concat(resultList)
          }
          let num = itemData.filter(function (item, index) {
            return item.sku_code == that.data.sku_code
          })
          if (num.length > 0) {
            let index = itemData.indexOf(num[0]);

            if (index >= 0) {
              num[0].current_num = 1;
              itemData.splice(index, 1);
              itemData.unshift(num[0]);
              that.setData({
                total_num: 1
              })
            }
          }
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            jiugui_total_page: totalPage,
            jiugui_items: itemData,
            items: (that.data.show_type == 1 ? itemData : that.data.pingtai_items)
          });
        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("登录失败，请检查网络");
      }
    })
  },
  //处理数据
  doData: function (list) {
    if (list.length <= 0) {
      return [];
    }
    var newList = [];
    for (var i = 0; i < list.length; i++) {
      var item = {
        id: list[i].id,
        images: list[i].image,
        name: list[i].gname,
        price: list[i].current_price,
        num: list[i].num,
        sku_code: list[i].sku_code,
        volume: list[i].volume,
        degree: list[i].degree,
        current_num: 0,
        isTouchMove: false,
      }
      newList.push(item)
    }
    return newList;
  },

  //平台购酒商品列表
  goodsList: function () {
    var that = this;
    api.POST({
      params: {
        page: that.data.pingtai_page,
        limit: that.data.limit,
      },
      url: app.globalData.base_url + 'goods/getList',
      success: function (res) {
        wx.hideLoading()
        if (util.isEmpty(res.data.code)) {
          var paging = res.data.data.search;
          var totalPage = paging.total_page;
          var currentPage = paging.page;
          var resultList = res.data.data.goods_list;
          resultList = that.doPingtaiData(resultList);
          if (currentPage == 1) {
            var itemData = resultList;
            if (itemData.length >= 1) {
              //有数据
            } else {
              //无数据
            }
          } else {
            var itemData = that.data.pingtai_items.concat(resultList)
          }
          that.setData({
            hasMore: (currentPage >= totalPage) ? false : true,
            pingtai_total_page: totalPage,
            pingtai_items: itemData,
            items: (that.data.show_type == 2 ? itemData : that.data.jiugui_items)
          });
        } else {
          util.showError(res.data.code);
        }
        wx.stopPullDownRefresh();
      },
      fail: function (fail) {
        wx.hideLoading()
        util.showError("登录失败，请检查网络");
      }
    })
  },
  //处理数据
  doPingtaiData: function (list) {
    if (list.length <= 0) {
      return [];
    }
    var newList = [];
    for (var i = 0; i < list.length; i++) {
      var item = {
        id: list[i].id,
        images: list[i].image,
        name: list[i].gname,
        price: list[i].current_price,
        num: '',
        sku_code: list[i].sku_code,
        volume: list[i].volume,
        degree: list[i].degree,
        current_num: 0,
        isTouchMove: false,
      }
      newList.push(item)
    }
    return newList;
  },

  //增加
  addNum: function (e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (that.data.show_type == 1) {
      if (info.current_num < info.num) {
        info.current_num = (info.current_num + 1)
        var items = that.data.jiugui_items
        items[i] = info;
        that.setData({
          items: items,
          jiugui_items: items
        })
        that.total_num(1)
      }
    } else {
      info.current_num = (info.current_num + 1)
      var items = that.data.pingtai_items
      items[i] = info;
      that.setData({
        items: items,
        pingtai_items: items
      })
      that.total_num(1)
    }

  },
  //减少
  minusNum: function (e) {
    var that = this;
    var info = e.currentTarget.dataset.info;
    var i = e.currentTarget.dataset.i;
    if (info.current_num >= 1) {
      info.current_num = (info.current_num - 1)
      var items = (that.data.show_type == 1 ? that.data.jiugui_items : that.data.pingtai_items)
      items[i] = info;
      if (that.data.show_type == 1) {
        that.setData({
          items: items,
          jiugui_items: items
        })
      } else {
        that.setData({
          items: items,
          pingtai_items: items
        })
      }
      that.total_num(2)
    }
  },
  //总数量
  total_num: function (type = 1) {
    var that = this;
    var total_num = this.data.total_num;
    var total_price = 0;
    var buyGoods = []
    var pingtai_items = that.data.pingtai_items;
    for (var i = 0; i < pingtai_items.length; i++) {
      if (pingtai_items[i].current_num > 0) {
        var box = {};
        box.sku_code = pingtai_items[i].sku_code;
        box.num = pingtai_items[i].current_num;
        buyGoods.push(box);
        var num = pingtai_items[i].current_num;
        var price = pingtai_items[i].price / 1;
        total_price += (num * price);
      }
    }
    this.setData({
      buyGoods: buyGoods,
      total_price: total_price,
      total_num: (type == 1) ? (total_num + 1) : (total_num - 1)
    })
  },

  //支付并生成礼品卡
  submit: function () {
    var that = this;
    if (that.data.total_num > 0) {
      if (that.data.buyGoods.length > 0) {
        //购买了平台商品，需支付
        that.payOrder();
      } else {
        that.createCard(); //生成礼品卡
      }
    }
  },

  // 支付订单
  payOrder: function () {
    var that = this;
    var buyGoods = that.data.buyGoods;
    var params = new Object()
    params.record = JSON.stringify(buyGoods)
    params.buy_type = 1;
    util.showLoading("加载中");
    api.POST({
      params: params,
      url: app.globalData.base_url + 'order/submit',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          wx.removeStorageSync('shopId')
          that.wxPayOrder(res.data.data.result.oid, res.data.data.result.type);
        } else if (res.data.code == "2499") {
          util.showError("库存不足");
        } else {
          // console.log(res.data);
          util.showError(res.data.message);
          // util.showError("库存不足");
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  //支付接口
  wxPayOrder: function (oid, types) {
    var params = new Object()
    var that = this;
    params.oid = oid;
    api.POST({
      params: { oid: oid },
      url: app.globalData.base_url + 'payment/getWechatInfo',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          var preData = res.data.data.payinfo;
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              that.createCard(); //生成礼品卡
            },
            fail: function (error) {
              util.showError("支付失败");
              wx.removeStorageSync('orderData');
            }
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  //生成礼品卡
  createCard: function () {
    var that = this;
    var index = that.data.current;
    var buyGoods = that.data.buyGoods;
    var jiugui_items = that.data.jiugui_items;
    for (var i = 0; i < jiugui_items.length; i++) {
      if (jiugui_items[i].current_num > 0) {
        var box = {};
        box.sku_code = jiugui_items[i].sku_code;
        box.num = jiugui_items[i].current_num;
        buyGoods.push(box);
      }
    }
    var params = new Object()
    params.record = JSON.stringify(buyGoods)
    params.cid = that.data.cardId;
    params.form_id = this.data.formId;
    params.img_id = that.data.cardImage[index].img_id;
    api.POST({
      params: params,
      url: app.globalData.base_url + 'giftcard/CreateCard',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          console.log('礼品卡成功')
          wx.redirectTo({
            url: '/play/pages/giftShare/giftShare?show_type=3&linkCode=' + res.data.data.linkCode
          })
        } else {
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },
  bindchange:function(e){
    // console.log(e);
    var current = e.detail.current;
    this.setData({
      current: current
    })
  },
  cardSelect:function(e){
    // console.log(e)
    var current = e.currentTarget.dataset.index
    this.setData({
      current: current
    })
  },
  //表单提交事件
  formSubmit: function (e) {

    var curTime = e.timeStamp;
    var lastTime = this.data.lastTime;
    this.setData({
      lastTime: curTime
    })
    if (lastTime > 0) {
      if (curTime - lastTime < 500) {
        return false;
      }
    }
    this.setData({
      formId: e.detail.formId
    })
    this.submit();
  }
})